package com.a3dweijing.wetouch2.Activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.Common.CallBack;
import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.AlerDialogHelp;
import com.a3dweijing.wetouch2.Util.ProgressDialogHelp;
import com.a3dweijing.wetouch2.network.RetrofitUtil;
import com.a3dweijing.wetouch2.adapter.ShoppingCartAcitivityAdapter;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.GoodsInfoBean;
import com.a3dweijing.wetouch2.bean.GoodsListBean;
import com.a3dweijing.wetouch2.bean.ResultMsg;
import com.a3dweijing.wetouch2.bean.ShoppingCartItem;
import com.a3dweijing.wetouch2.constant.Api;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.a3dweijing.wetouch2.Activity.BuyActivity.BUYACTIVITYCODE;

public class ShoppingCartActivity extends BaseActivity implements View.OnClickListener
{
    
    @BindView(R.id.back)
    ImageView back;
    
    @BindView(R.id.top_text)
    TextView topText;
    
    @BindView(R.id.top_right)
    TextView topRight;
    
    @BindView(R.id.top_all)
    RelativeLayout topAll;
    
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    
    @BindView(R.id.loading_date)
    LinearLayout loadingDate;
    
    @BindView(R.id.resaut_status_img)
    ImageView resautStatusImg;
    
    @BindView(R.id.resaut_status)
    LinearLayout resautStatus;
    
    @BindView(R.id.listview)
    ListView listview;
    
    @BindView(R.id.all_cb)
    CheckBox allcb;
    
    @BindView(R.id.sbmit)
    Button sbmit;
    
    private ShoppingCartAcitivityAdapter adapter;
    
    private ProgressDialog dialog;
    
    private ArrayList<GoodsListBean> items;
    
    private Call<JsonObject> delete;
    
    private AlertDialog adialog;
    
    private static ArrayList<Integer> ints = new ArrayList<>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shoppint_cart);
        ButterKnife.bind(this);
        initView();
        initDate();
        setOnClick();
    }
    
    @Override
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.top_right:
                delete();
            case R.id.all_cb:
                HashMap<Integer, Boolean> map = adapter.getMap();
                for (Map.Entry<Integer, Boolean> entry : map.entrySet())
                {
                    entry.setValue(allcb.isChecked());
                }
                adapter.notifyDataSetChanged();
                sbmit.setText("结算：(" + map.size() + ")");
                break;
            case R.id.back:
                finish();
                break;
            case R.id.sbmit:
                HashMap<Integer, Boolean> map1 = adapter.getMap();
                ArrayList<GoodsInfoBean> goodsInfoBeans = new ArrayList<>();
                for (Map.Entry<Integer, Boolean> entry : map1.entrySet())
                {
                    if (entry.getValue())
                    {
                        GoodsListBean goodsListBean = items.get(entry.getKey());
                        GoodsInfoBean b = new GoodsInfoBean();
                        b.setS_goods_name(goodsListBean.getGoods_name());
                        b.setS_goods_id(goodsListBean.getGoods_id());
                        b.setS_goods_img_url(goodsListBean.getGoods_img());
                        b.setS_price(goodsListBean.getGoods_money());
                        b.setNumber(goodsListBean.getGoods_number());
                        goodsInfoBeans.add(b);
                    }
                }
                if (goodsInfoBeans.size() == 0)
                    Toast.makeText(this, "请选择至少一个物品", Toast.LENGTH_SHORT).show();
                else
                    BuyActivity.startActivity(this, goodsInfoBeans);
                break;
        }
    }
    
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (delete != null && !delete.isCanceled())
            delete.cancel();
    }
    
    private void delete()
    {
        if (items == null)
        {
            return;
        }
        else
        {
            HashMap<Integer, Boolean> map = adapter.getMap();
            ints.clear();
            for (Map.Entry<Integer, Boolean> entry : map.entrySet())
            {
                if (entry.getValue())
                {
                    ints.add(items.get(entry.getKey()).getGoods_id());
                }
            }
            if (ints.size() == 0)
                Toast.makeText(this, "请至少选择一个目标", Toast.LENGTH_SHORT).show();
            else
            {
                if (adialog == null)
                    adialog = new AlerDialogHelp().create(this, "提示", "你是否要删除该商品", true, new CallBack()
                    {
                        @Override
                        public void doNext(int what, Object obj)
                        {
                            dialog.show();
                            String id = "";
                            for (int i = 0; i < ints.size(); i++)
                            {
                                id += ints.get(i) + ",";
                            }
                            id = id.substring(0, id.length() - 1);
                            delete = RetrofitUtil.getInstance().getApiOfPhp().delete(id);
                            delete.enqueue(new Callback<JsonObject>()
                            {
                                @Override
                                public void onResponse(Call<JsonObject> call, Response<JsonObject> response)
                                {
                                    dialog.dismiss();
                                    ResultMsg resultMsg = new Gson().fromJson(response.body(), ResultMsg.class);
                                    if (resultMsg != null && resultMsg.isFlag())
                                    {
                                        for (int i = items.size() - 1; i >= 0; i--)
                                        {
                                            for (Integer anInt : ints)
                                            {
                                                if (items.get(i).getGoods_id() == anInt)
                                                {
                                                    items.remove(i);
                                                    break;
                                                }
                                            }
                                        }
                                        adapter.resetmap();
                                        adapter.notifyDataSetChanged();
                                        if (items.size() == 0)
                                            resautStatus.setVisibility(View.VISIBLE);
                                    }
                                    else
                                    {
                                        Toast.makeText(ShoppingCartActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                                        
                                    }
                                }
                                
                                @Override
                                public void onFailure(Call<JsonObject> call, Throwable t)
                                {
                                    Toast.makeText(ShoppingCartActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                }
                            });
                        }
                    });
                adialog.show();
            }
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BUYACTIVITYCODE && resultCode == RESULT_OK)
        {
            OrderListActivity.startActivity(ShoppingCartActivity.this, 0);
            finish();
        }
    }
    
    private void setOnClick()
    {
        allcb.setOnClickListener(this);
        back.setOnClickListener(this);
        sbmit.setOnClickListener(this);
        topRight.setOnClickListener(this);
    }
    
    private void initDate()
    {
        loadingDate.setVisibility(View.VISIBLE);
        resautStatus.setVisibility(View.GONE);
        Api api = RetrofitUtil.getInstance().getApiOfPhp();
        Observable<ShoppingCartItem> observable =
            api.shoppingCartlist(Integer.parseInt(Singleton.getInstance().getUser().getUser_id()));
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
            new Observer<ShoppingCartItem>()
            {
                @Override
                public void onSubscribe(Disposable d)
                {
                    disposables.add(d);
                }
                
                @Override
                public void onNext(ShoppingCartItem shoppingCartItem)
                {
                    if (shoppingCartItem.isFlag() && shoppingCartItem.getGoodsList() != null
                        && shoppingCartItem.getGoodsList().size() > 0)
                    {
                        items.clear();
                        items.addAll(shoppingCartItem.getGoodsList());
                        adapter.resetmap();
                        adapter.notifyDataSetChanged();
                    }
                    else
                        resautStatus.setVisibility(View.VISIBLE);
                }
                
                @Override
                public void onError(Throwable e)
                {
                    loadingDate.setVisibility(View.GONE);
                    resautStatus.setVisibility(View.VISIBLE);
                }
                
                @Override
                public void onComplete()
                {
                    loadingDate.setVisibility(View.GONE);
                }
            });
    }
    
    private void initView()
    {
        topRight.setText("删除");
        topText.setText("购物车");
        dialog = ProgressDialogHelp.create(this, "提示", "提交中...", false);
        items = new ArrayList<>();
        adapter = new ShoppingCartAcitivityAdapter(this, items, R.layout.shoppintcart_item, new CallBack()
        {
            @Override
            public void doNext(int what, Object obj)
            {
                if (obj == null)
                {
                    HashMap<Integer, Boolean> map = adapter.getMap();
                    boolean isCheck = true;
                    int i = 0;
                    for (Map.Entry<Integer, Boolean> entry : map.entrySet())
                    {
                        if (entry.getValue())
                            i++;
                        else
                            isCheck = false;
                    }
                    allcb.setChecked(isCheck);
                    sbmit.setText("结算：(" + i + ")");
                }
                else
                {
                    if ((int)obj == R.id.add)
                    {
                        addOrJian(what, 1);
                    }
                    else if ((int)obj == R.id.jian)
                    {
                        addOrJian(what, 2);
                    }
                    
                }
            }
        });
        listview.setAdapter(adapter);
    }
    
    private void addOrJian(final int position, final int i)
    {
        final int goods_number = items.get(position).getGoods_number();
        if (i == 1 && goods_number >= 10)
        {
            
            Toast.makeText(this, "不能再添加了", Toast.LENGTH_SHORT).show();
            return;
        }
        else if (i == 2 && goods_number <= 1)
        {
            Toast.makeText(this, "不能再减少了", Toast.LENGTH_SHORT).show();
            return;
        }
        else
        {
            dialog.show();
            Api api = RetrofitUtil.getInstance().getApiOfPhp();
            Call<JsonObject> call = api.addOrJian(items.get(position).getGoods_id(), i);
            calls.add(call);
            call.enqueue(new Callback<JsonObject>()
            {
                @Override
                public void onResponse(Call<JsonObject> call, Response<JsonObject> response)
                {
                    dialog.dismiss();
                    ResultMsg resultMsg = new Gson().fromJson(response.body(), ResultMsg.class);
                    if (resultMsg.isFlag())
                    {
                        if (i == 1)
                            items.get(position).setGoods_number(goods_number + 1);
                        else
                        {
                            items.get(position).setGoods_number(goods_number - 1);
                        }
                        adapter.notifyDataSetChanged();
                    }
                }
                
                @Override
                public void onFailure(Call<JsonObject> call, Throwable t)
                {
                    Toast.makeText(ShoppingCartActivity.this, "网络出错了...", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });
        }
    }
    
}
